from rest_framework import permissions
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ImproperlyConfigured


class HasDjangoPermission(permissions.BasePermission):
    """
    To use this permission class, override `get_permissions()` method in your view
    class.
    """

    def __init__(
        self, permission_required: list, authenticated_users_only: bool = True
    ):
        self.permission_required = permission_required
        self.authenticated_users_only = authenticated_users_only

    def has_permission(self, request, view):
        if not self.permission_required:
            raise ImproperlyConfigured(
                "%(view)s - %(cls)s doesn't initialize `permission_required` field."
                % {"view": view, "cls": self.__class__.__name__}
            )

        user: AbstractUser = request.user
        if not user or (not user.is_authenticated and self.authenticated_users_only):
            return False

        permissions = (
            self.permission_required
            if hasattr(self.permission_required, "__iter__")
            else [self.permission_required]  # [None] is OK
        )

        if user.has_perms(permissions):
            return True

        return False
